/**
 * <p>Copyright(C) 2018 Hangzhou Differsoft Co., Ltd. All rights reserved.</p>
 */
package com.utils.query;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.constants.Constants;


/**
 * <p>
 * 类描述: 文件工具类
 * </p>
 *
 * @author wengjiaxin
 * @since 2020年05月09日
 */
public class FileUtils {
    private static final Logger LOG = LoggerFactory.getLogger(FileUtils.class);

    /**
     * MD5
     **/
    private static final String MD5 = "MD5";
    /**
     * 1024
     **/
    private static final int BYTE_MAX = 1024;

    /**
     *
     */
    private FileUtils() {
        super();
    }

    /**
     * 计算字符串的Content-MD5
     *
     * @param file
     *            文件
     * @return 文件MD5
     */
    public static String getStringContentMD5(File file) {
        // 获取文件MD5的二进制数组（128位）
        byte[] bytes = getFileMD5Bytes128(file);
        // 读文件异常时，返回null
        if (bytes == null) {
            return null;
        }
        // 对文件MD5的二进制数组进行base64编码
        return new String(Base64.encodeBase64(bytes));
    }

    /**
     * <p>
     * 将文件转成base64 字符串
     * </p>
     *
     * @param file
     *            文件
     * @return base64
     */
    public static String encodeBase64File(File file) {
        byte[] buffer = null;
        try (FileInputStream inputFile = new FileInputStream(file)) {
            buffer = new byte[(int) file.length()];
            // 将内容读取内存中
            int len = -1;
            while ((len = inputFile.read(buffer)) != -1) {
                inputFile.read(buffer, 0, len);
            }
        } catch (Exception e) {
            LOG.error("获取文件base64-二进制数组失败", e);
        }
        return new String(Base64.encodeBase64(buffer));
    }

    /**
     * 获取文件MD5-二进制数组（128位）
     *
     * @param file
     *            文件
     * @return 文件MD5-二进制数组
     */
    public static byte[] getFileMD5Bytes128(File file) {
        byte[] md5Bytes = null;
        try (FileInputStream fis = new FileInputStream(file)) {
            MessageDigest md5 = MessageDigest.getInstance(MD5);
            byte[] buffer = new byte[BYTE_MAX];
            int length;
            while ((length = fis.read(buffer, 0, BYTE_MAX)) != -1) {
                md5.update(buffer, 0, length);
            }
            md5Bytes = md5.digest();
        } catch (Exception e) {
            LOG.error("获取文件MD5-二进制数组失败", e);
        }
        return md5Bytes;
    }

    /**
     * 获取文件字节流
     *
     * @param file
     *            文件
     * @return 文件字节流
     */
    public static byte[] getBytes(File file) {
        byte[] buffer = null;
        try (FileInputStream fis = new FileInputStream(file)) {
            buffer = new byte[(int) file.length()];
            int reads = fis.read(buffer);
            if (reads == -1) {
                LOG.error("获取文件字节流失败");
            }
        } catch (Exception e) {
            LOG.error("获取文件字节流失败", e);
        }
        return buffer;
    }

    /**
     * 读取文本文件内容
     *
     * @param in
     *            文件流对象
     * @return 文本文件内容
     * @throws IOException
     * @author goofus
     */
    public static String readTextFile(InputStream in, String charsetName) throws IOException {
        StringBuilder text = new StringBuilder();

        if (null == charsetName || charsetName.trim().length() < 1) {
            charsetName = "UTF-8";
        }
        InputStreamReader isr = new InputStreamReader(in, charsetName);

        try {
            char[] buf = new char[40960];
            int len = -1;
            while ((len = isr.read(buf)) > 0) {
                text.append(new String(buf, 0, len));
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != in) {
                in.close();
            }
        }

        return text.toString();
    }

}
